package com.mall.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mall.common.response.CommonResponse;
import com.mall.constant.enums.CommonStatus;
import com.mall.common.response.CommonResponse;
import com.mall.constant.enums.CommonStatus;
import com.mall.constant.strings.ErrorMsg;
import com.mall.constant.strings.SuccessMsg;
import com.mall.constant.strings.IntStant;
import com.mall.entity.TbUser;
import com.mall.user.dao.UserMapper;
import com.mall.user.mq.Producer;
import com.mall.user.service.TokenService;
import com.mall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户服务impl
 *
 * @author ASUS
 * @date 2021/07/18
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Producer producer;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenService tokenService;

    @Override
    public CommonResponse sendYzm(String tel) {
        if (tel==null || "".equals(tel)){
            return new CommonResponse(CommonStatus.UNVALID.getCode(), ErrorMsg.ERROR_PARAM_404);
        }else{
            //定义验证码
            String yzm = "";
            for (int i = 0; i < IntStant.IntStatus.ARRAY_LENGTH_4; i++) {
                Random random = new Random();
                yzm += random.nextInt(9)+1;
            }
            System.out.println(yzm);
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("tel",tel);
            map.put("yzm",yzm);
            //将验证码存入redis
            redisTemplate.opsForValue().set(tel,yzm,1, TimeUnit.MINUTES);
            //通过mq发送短信
            producer.sendYzm(JSONObject.toJSONString(map));
            return new CommonResponse(CommonStatus.VALID.getCode(), SuccessMsg.SUCCESS_CODE_200);
        }
    }

    @Override
    public CommonResponse login(TbUser user) {
        TbUser userForBase=userMapper.findUserById(user.getTel());
        if(userForBase==null){
            return new CommonResponse(CommonStatus.UNVALID.getCode(), ErrorMsg.ERROR_USER_ID_NULL_404);
        }else {
            if (!userForBase.getPwd().equals(user.getPwd())){
                return new CommonResponse(CommonStatus.UNVALID.getCode(), ErrorMsg.ERROR_USERNAME_AND_PWD_404);
            }else {
                String token = tokenService.getToken(userForBase);
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                redisTemplate.opsForValue().set(token,userForBase);
                return new CommonResponse(CommonStatus.VALID.getCode(), SuccessMsg.SUCCESS_LOGIN_200,jsonObject);
            }
        }
    }

    @Override
    public CommonResponse register(String tel, String yzm) {
        TbUser u = userMapper.selectTel(tel);
        if (u!=null){
            return new CommonResponse(CommonStatus.UNVALID.getCode(), ErrorMsg.ERROR_USEREXITES_404);
        }else{
            //获取验证码
            String code = (String) redisTemplate.opsForValue().get(tel);
            if (code==null){
                //如果验证码为空则失效
                return new CommonResponse(CommonStatus.UNVALID.getCode(), ErrorMsg.ERROR_SHIXIAO_404);
            }else{
                //如果验证码不为空就和传入的做比较
                if (code.equals(yzm)){
                    //比较成功进行注册
                    TbUser user = new TbUser();
                    user.setTel(tel);
                    user.setName("新用户");
                    userMapper.insert(user);
                    return new CommonResponse(CommonStatus.VALID.getCode(), SuccessMsg.SUCCESS_CODE_200);
                }else{
                    //如果为空则返回提示信息
                    return new CommonResponse(CommonStatus.UNVALID.getCode(), ErrorMsg.ERROR_OPERATION_404);
                }
            }
        }
    }

    @Override
    public CommonResponse setPassword(TbUser user) {
        //先查询是否存在该用户
        TbUser u = userMapper.findOneByTel(user);
        if (u!=null){
            //如果存在则修改密码
            u.setPwd(user.getPwd());
            userMapper.update(u);
            return new CommonResponse(CommonStatus.VALID.getCode(), SuccessMsg.SUCCESS_CODE_200);
        }else{
            return new CommonResponse(CommonStatus.UNVALID.getCode(), ErrorMsg.ERROR_USER_ID_NULL_404);
        }


    }

    @Override
    public CommonResponse<TbUser> getPersonalDetails(String tel) {
        //根据电话查询用户信息
        TbUser user = new TbUser();
        user.setTel(tel);
        TbUser u = userMapper.findOneByTel(user);
        return new CommonResponse(CommonStatus.VALID.getCode(), SuccessMsg.SUCCESS_CODE_200,u);
    }

    @Override
    public TbUser findUserById(String userId) {
        return userMapper.findUserById(userId);
    }

    @Override
    public void updateAccumulativeTotalByUid(Long uid, BigDecimal rechargeAmount) {
        userMapper.updateAccumulativeTotalByUid(uid,rechargeAmount);
    }

}
